package com.qilu.careprogram.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qilu.careprogram.dao.MessageAlertDAO;
import com.qilu.careprogram.pojo.entity.Question;
import com.qilu.careprogram.pojo.entity.Answer;
import com.qilu.careprogram.service.SmartQaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SmartQaServiceImpl implements SmartQaService {

    // 直接在代码中定义配置参数
    private static final String BASE_URL = "http://211.87.236.79:8099";
    private static final String API_KEY = "ragflow-NmODBmOTU4NWFmNjExZjBiMmFhMWFjMG";
    private static final String CHAT_ID = "1ae0be3457b411f09e561ac0b3e3932f";

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private MessageAlertDAO messageAlertDAO;

    @Override
    public String createSession() {
        try {
            String url = BASE_URL + "/api/v1/chats/" + CHAT_ID + "/sessions";

            // 打印调试信息
            System.out.println("请求URL: " + url);
            System.out.println("API_KEY: " + API_KEY.substring(0, 5) + "...");

            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + API_KEY);
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 简化请求体
            Map<String, String> requestBody = Collections.singletonMap("name", "API会话");

            ResponseEntity<Map> response = restTemplate.postForEntity(
                    url,
                    new HttpEntity<>(requestBody, headers),
                    Map.class
            );

            System.out.println(response.getBody());

            // 增强响应解析
            if (response.getStatusCode() == HttpStatus.OK) {
                Map<String, Object> body = response.getBody();
                if (body != null && (Integer)body.get("code") == 0) {
                    Map<String, Object> data = (Map<String, Object>) body.get("data");
                    System.out.println( data);
                    String sessionId = (String) data.get("id");
                    System.out.println( sessionId);
                    return sessionId;
                } else if (body != null) {
                    throw new RuntimeException("创建会话失败: " + body.get("message"));
                }
            }
            throw new RuntimeException("响应格式异常: " + response.getBody());
        } catch (Exception e) {
            throw new RuntimeException("创建会话失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void chatStream(String sessionId, String question, String hospitalNumber, OutputStream outputStream) {
        String url = BASE_URL + "/api/v1/chats/" + CHAT_ID + "/completions";
        System.out.println("===== 开始流式请求 =====");
        System.out.println("请求URL: " + url);
        System.out.println("SessionID: " + sessionId);
        System.out.println("问题: " + question);

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + API_KEY);
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("question", question);
        requestBody.put("session_id", sessionId);
        requestBody.put("stream", true);

        try {
            System.out.println("请求体: " + objectMapper.writeValueAsString(requestBody));
        } catch (Exception e) {
            System.err.println("序列化请求体失败: " + e.getMessage());
        }

        // 使用容器解决Lambda变量限制问题
        final StringBuilder fullAnswer = new StringBuilder();
        final boolean[] isReferencedHolder = new boolean[]{false};

        // 使用自定义响应处理器处理流式响应
        restTemplate.execute(url, HttpMethod.POST,
                request -> {
                    request.getHeaders().addAll(headers);
                    byte[] bodyBytes = objectMapper.writeValueAsBytes(requestBody);
                    request.getBody().write(bodyBytes);
                    System.out.println("已发送请求到RagFlow, 内容长度: " + bodyBytes.length);
                },
                response -> {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8))) {
                        String line;
                        // 存储最后发送的答案
                        String lastSentAnswer = "";
                        int lineCount = 0;
                        int dataCount = 0;

                        System.out.println("===== 开始接收流式响应 =====");

                        while ((line = reader.readLine()) != null) {
                            lineCount++;
                            System.out.println("原始行[" + lineCount + "]: " + line);

                            // 忽略空行
                            if (line.isEmpty()) {
                                System.out.println("跳过空行");
                                continue;
                            }

                            if (line.startsWith("data:")) {
                                String jsonStr = line.replaceFirst("^data:\\s*", "");
                                dataCount++;
                                System.out.println("解析数据块[" + dataCount + "]: " + jsonStr);

                                try {
                                    JsonNode node = objectMapper.readTree(jsonStr);
                                    int code = node.path("code").asInt();

                                    if (code != 0) {
                                        System.err.println("RagFlow返回错误码: " + code);
                                        System.err.println("错误信息: " + node.path("message").asText());
                                        continue;
                                    }

                                    JsonNode dataNode = node.path("data");

                                    if (dataNode.isBoolean() && dataNode.asBoolean()) {
                                        System.out.println("收到流结束标志");
                                        continue;
                                    }

                                    if (dataNode.isObject() && dataNode.has("answer")) {
                                        String currentAnswer = dataNode.get("answer").asText();
                                        System.out.println("当前答案: " + currentAnswer);
                                        System.out.println("上次发送: " + lastSentAnswer);

                                        // 检查参考来源
                                        if (dataNode.has("reference") &&
                                                !dataNode.get("reference").isNull() &&
                                                !dataNode.get("reference").asText().isEmpty()) {
                                            isReferencedHolder[0] = true;
                                            System.out.println("检测到参考来源");
                                        }

                                        // 计算增量内容
                                        String toSend = "";
                                        if (currentAnswer.startsWith(lastSentAnswer)) {
                                            toSend = currentAnswer.substring(lastSentAnswer.length());
                                        } else {
                                            System.err.println("警告: 答案不连续! 发送完整答案");
                                            toSend = currentAnswer;
                                        }

                                        if (!toSend.isEmpty()) {
                                            System.out.println("发送内容: " + toSend);
                                            outputStream.write(toSend.getBytes(StandardCharsets.UTF_8));
                                            outputStream.flush();
                                            lastSentAnswer = currentAnswer;

                                            // 累积到完整答案
                                            fullAnswer.append(toSend);
                                        } else {
                                            System.out.println("无新增内容，跳过");
                                        }
                                    }
                                } catch (Exception e) {
                                    System.err.println("解析JSON错误: " + e.getMessage());
                                    System.err.println("原始JSON: " + jsonStr);
                                }
                            }
                        }
                        System.out.println("===== 流式响应处理完成 =====");
                        System.out.println("总处理行数: " + lineCount + ", 有效数据块: " + dataCount);

                        // 流结束后处理完整答案
                        String completeAnswer = fullAnswer.toString();
                        System.out.println("完整答案: " + completeAnswer);

                        // 若无参考来源则添加提示 - 修改开始
                        String additionalNote = "";
                        if (!isReferencedHolder[0]) {
                            additionalNote = "该问题的答案由GPT生成，仅供参考";
                            System.out.println("添加无参考来源提示");

                            // 将提示发送给前端
                            try {
                                outputStream.write(additionalNote.getBytes(StandardCharsets.UTF_8));
                                outputStream.flush();
                                System.out.println("已发送无参考来源提示给前端");
                            } catch (IOException e) {
                                System.err.println("发送提示失败: " + e.getMessage());
                            }
                        }

                        // 构建最终答案（包含可能的提示）
                        String finalCompleteAnswer = completeAnswer + additionalNote;
                        // 若无参考来源则添加提示 - 修改结束

                        // 截断答案（使用完整答案+提示）
                        String finalAnswer = finalCompleteAnswer;
                        if (finalCompleteAnswer.length() > 255) {
                            finalAnswer = finalCompleteAnswer.substring(0, 253) + "...";
                            System.out.println("答案截断至120字符");
                        }

                        // 插入问题记录
                        Question newQuestion = new Question();
                        newQuestion.setHospitalNumber(hospitalNumber);
                        newQuestion.setText(question);
                        newQuestion.setCreateTime(LocalDateTime.now());
                        newQuestion.setUpdateTime(LocalDateTime.now());
                        newQuestion.setStatus(isReferencedHolder[0]);  // 状态表示是否有参考来源
                        messageAlertDAO.insertQuestion(newQuestion);

                        // 获取问题ID
                        Long questionId = messageAlertDAO.getQuestionIdByHospitalNumberAndText(hospitalNumber);
                        System.out.println("插入问题记录，ID: " + questionId);

                        // 插入答案记录
                        Answer newAnswer = new Answer();
                        newAnswer.setQuestionId(questionId);
                        newAnswer.setSource(2);  // 固定来源值2
                        newAnswer.setText(finalAnswer);
                        newAnswer.setIsused(isReferencedHolder[0]);  // 标记是否参考
                        newAnswer.setCreateTime(LocalDateTime.now());
                        messageAlertDAO.insertAnswer(newAnswer);
                        System.out.println("插入答案记录，内容: " + finalAnswer);

                    } catch (IOException e) {
                        System.err.println("流读取异常: " + e.getMessage());
                    }
                    return null;
                }
        );
    }

    @Override
    public void deleteSession(String sessionId) {
        String url = BASE_URL + "/api/v1/chats/" + CHAT_ID + "/sessions";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + API_KEY);
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, List<String>> requestBody = new HashMap<>();
        requestBody.put("ids", Collections.singletonList(sessionId));

        HttpEntity<Map<String, List<String>>> request = new HttpEntity<>(requestBody, headers);

        // 使用exchange发送DELETE请求
        restTemplate.exchange(url, HttpMethod.DELETE, request, Void.class);
    }
}